<template>
  <div class="wrapper">
    <div class="header">
      <span class="return" @click="renturnAddressList()">返回</span>创建群<span @click="createGroup()" class="send">完成</span>
    </div>
    <div @click="chyangeFaceUrl()" class="groupItem">
      <img :onerror="defaultImg"  :src="groupData.faceUrl" alt="">
      <div class="Set">选择头像<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
    </div>
    <div class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <router-link to="/createGroupSetName">
      <div class="myCardTitle"> <!-- @click="showSetGroupNameWrapper()" -->
        群名称<div class="Set">{{groupData.groupName?groupData.groupName:"未设置"}}<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
      </router-link>
    </div>
    <div class="selectedFriendsTitle">已选好友</div>
    <router-link to="/createGroupApplyJoin">
    <div class="selectedFriends"> <!-- @click="showInviteFriendWrapper()" -->
      <div class="friendList">
        <img  class="icon" src="../../assets/img/icon_group@3x.png" alt="">
        <div class="faceItem">     
          <img :onerror="defaultImg" v-for="(item, index) in groupData.groupMembers" v-if="index < 3" :src="item.friendUrl" alt="">
          <img src="../../assets/img/icon_addfm@3x.png" alt="">
        </div>
      </div>
      <div class="Set">已选{{groupData.groupMembers.length}}名<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
    </div>
    </router-link>
    <div class="divisionLine"></div>
    
    <div class="myCard">
      <!-- <router-link to="/createGroupSetId"> -->
      <div class="myCardTitle">
        群组ID<div class="Set">{{groupId}}</div>
      </div>
      <!-- </router-link> -->
    </div>
    <div class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <div class="myCardTitle" @click="showgroupTypeWrap()">
        群类型<div class="Set">{{groupData.groupTypeZn[groupData.groupType]}}<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
    </div>
    <div v-show="groupData.groupType == 'Public' || groupData.groupType == 'ChatRoom'" class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <div class="myCardTitle"  @click="showchangeTypeWrap()">
        加群方式<div class="Set">{{joinGroupType}}<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
    </div>
    <div class="divisionLine"></div>
    <router-link to="/createGroupSetInfo">
    <div class="groupInfo">
      <div>
        <p class="groupName">群介绍</p>
        <p class="text">{{groupData.groupInfo?groupData.groupInfo:"群介绍不等超过40字"}}</p>
      </div>
      <div class="Set"><img src="../../assets/img/icon_shape@3x.png" alt=""></div>
    </div>
    </router-link>
  <!-- 底部菜单 -->
    <mt-actionsheet :actions="acti" v-model="sheetVisible"></mt-actionsheet>
    <!-- 文件上传-->
    <form id="uploadForm" ref="uploadForm">
      <input type="file" @change="changeFile" ref="uploadFileId">
    </form>
  <!-- 设置群组类型 -->
  <mt-actionsheet
    :actions="actions"
    v-model="popup.groupTypeWrap">
  </mt-actionsheet>
  <!-- 设置群组类型 -->

  <!-- 设置群组类型 -->
  <mt-actionsheet
    :actions="actionss"
    v-model="popup.changeTypeWrap">
  </mt-actionsheet>
  <!-- 设置群组类型 -->
  </div>
</template>
<script>
import Client from '../../assets/js/common';
import { Popup } from 'mint-ui';
import { Actionsheet } from 'mint-ui';
import { MessageBox } from 'mint-ui';
import CosCloud from '../../../static/cos-js-sdk-v4'
import {axiosPost} from '../../assets/api'
import {Toast, Indicator} from 'mint-ui'
import {checkStatus} from '../../assets/js/login';

export default {
  data () {
    return {
      defaultImg: Client.defaultGroupImg,
      sheetVisible: false,
      loginInfo: {},
      acti:[
        {name: '相册', method: this.takePhoto},
      ],
      groupId: '自动生成',
      actions:[
        {name: '聊天室', method: this.selectedChatRoom},
        {name: '公开群', method: this.selectedPublic},
        {name: '私有群', method: this.selectedPrivate}
      ],
      actionss: [
        {name: "自由出入", method: this.freeaccess},
        {name: "需要验证", method: this.needpermission},
        {name: "禁止加入", method: this.disableapply},
      ],
      friendList: [], // 好友列表
      popup:{ // 弹出层
         groupTypeWrap: false, // 设置群类型的层
         changeTypeWrap: false // 设置加群类型的层
      },
      changeData: { // 正在修改的数据
        groupName: '', // 正在修改的群组名称 
        groupMembers:[],  // 正在修改的群组邀请好友加入列表
        groupId: '', // 正在修改的群组ID
        groupInfo: '' // 正在修改群介绍
      },
      groupData: { // 群组信息
        faceUrl: '', // 群组头像
        groupName: '', // 群组名称
        groupMembers: [], // 邀请加群的好友列表
        groupId: '', // 群组ID
        groupType: 'Public', // 群组类型
        groupTypeZn: {'Public': '公开群','Private': '私有群','ChatRoom': '聊天室'},
        applyJoinType: 'NeedPermission', // 加群类型
        groupInfo: '' // 群组简介
      },
      sdkAppID: "",
      joinGroupType: '需要验证',
      cosdata: '',
      groupMsc: {},
      cos: ''

    }
  },
  created() {
    // 登录
    checkStatus((loginInfo) => {
      this.getAll(loginInfo);
      this.loginInfo = loginInfo;
      this.autoGetGroupId(Client.getStore('userLogin').AppId);
      this.friendList = Client.getStore('friendList');
      this.initcreateGroupInfo();
      console.log( Client.getStore("createGroupInfo"));
    });
    
  },
  methods: {
    chyangeFaceUrl() {
      this.sheetVisible = true;
    },
    autoGetGroupId(myAppID) {
      let That = this;
      let appId = "" + myAppID;
      axiosPost({
        data: {"AppId": appId},
        url: 'GroupManager/GetNewGroupId?token=123&appSecret=8888',
        onSuccess (res) {
          That.groupData.groupId = res.data.Result;

        },
        onFailure (err) {
          Toast("自动获取Id失败")
          console.log("失败弟弟嘟嘟", err);
          console.log("aaa", appId);
        }
      })
    },
    
    // 拍照
      takePhoto(){
        this.$refs.uploadFileId.click();
      },
      // 上传头像
      changeFile(e){
        console.log(e);
        let That = this
        let apiname = "upload/uploadHeadPic";
        axiosPost({
          data: {
            "fileEtension": "jpg",
            "signType": 0
          },
          url: apiname + '?token=123&appSecret=8888',
          onSuccess (res) {
            That.cosdata = res.data.Result;
            console.log(That.cosdata)
            That.cos = new CosCloud({
              appid: That.cosdata.appid, // APPID 必填参数
              bucket: That.cosdata.bucket, // bucketName 必填参数
              region: That.cosdata.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
              getAppSign: function (callback) {
                callback(That.cosdata.AppSign);
              },//多次签名 可使用多次
              getAppSignOnce: function (callback) {

                 callback(That.cosdata.AppSignOnce);
              }
            });
            That.uploadFile(e)
          },
          onFailure (res) {
            console.log(res)
          }
        })
      },

      // 文件上传
      uploadFile(e){
        let That = this
        //let myFolder = 'head/';//需要操作的目录

        let successCallBack = function (result) {
          //console.log(That.groupData.faceUrl);
          Indicator.close();
          if(result.code !== 0){
            Toast('图片上传失败');
            return;
          }else{
            That.groupData.faceUrl = result.data.access_url;
            That.changeStorage('createGroupInfo', 'faceUrl', result.data.access_url, null);
            Toast('图片上传成功');
          }
        };
        
        let errorCallBack = function (result) {
          Indicator.close();
          result = result || {};
          console.log('request error:', result && result.message);
        };


        let progressCallBack = function (curr, sha1) {
          let sha1CheckProgress = ((sha1 * 100).toFixed(2) || 100) + '%';
          let uploadProgress = ((curr || 0) * 100).toFixed(2) + '%';
          let msg = 'upload progress:' + uploadProgress + '; sha1 check:' + sha1CheckProgress + '.';
          // if (uploadProgress === '100.00%') {
          //   Indicator.close();
          //   Toast('图片上传成功')
          //   // _this.isSet = true
          // }
        };

        let lastTaskId;
        let taskReady = function (taskId) {
          lastTaskId = taskId;
        };
        let file = e.target.files[0];
        let fileLimit = 1024 * 1024 * 20   // 1M图片限制
        if (!file.type.includes('image')) {
          Toast("请上传图片格式的文件")
          this.$refs.uploadForm.reset()
          return false
        }
        if (file.size > fileLimit) {
          Toast('请上传20M以内的图片')
          this.$refs.uploadForm.reset()
          return false
        }
        // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传
        Indicator.open();
        this.cos.uploadFile(successCallBack, errorCallBack, progressCallBack, this.cosdata.bucket,
          this.cosdata.fileName, file, 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
        return false;
      },
      
      

      //获取全部好友
      getAll(loginInfo) {	
      //Client.log(loginInfo);
        let getAllFriend = (cbOK, cbErr) => {
          let options = {
            From_Account: loginInfo.identifier,
            TimeStamp: 0,
            StartIndex: 0,
            GetCount: 100, //totalCount,
            LastStandardSequence: 0,
            TagList: [
              "Tag_Profile_IM_Nick",
              "Tag_Profile_IM_SelfSignature", //个性签名
              "Tag_Profile_IM_Image", //头像
              "Tag_Profile_IM_Gender", //性别
              "Tag_Profile_IM_AllowType", //加好友验证方式
              "Tag_Profile_IM_Location", //所在地
              "Tag_Profile_IM_BirthDay", //生日
              "Tag_Profile_IM_MsgSettings" //消息设置 置0表示接收消息，置1则不接收消息
            ]
          };
          webim.getAllFriend(
            options,
            (resp) => {
              Client.log(resp);
          if (resp.FriendNum > 0) {
          //转化成对象挂载到数据
            for(let i=0;i<resp.InfoItem.length;i++){
              if(resp.InfoItem[i].SnsProfileItem){
                let sns = resp.InfoItem[i].SnsProfileItem;
                sns.forEach((ele,index) => {
                resp.InfoItem[i][ele.Tag]=ele.Value;
                });
            //清空原来的resp.InfoItem[i].SnsProfileItem = '';
              }
            }

          this.friendList = resp.InfoItem;
          Client.log(this.friendList);
          let friends = resp.InfoItem;
          //存储好友列表
          Client.setStore('friendList',friends);
          //Client.log(Client.getStore('friendList'));
                if (cbOK) cbOK();
              }
            },
            (err) => {
              Client.errInfo();
              // alert(err.ErrorInfo);
            }
          );
      };
      getAllFriend();
    },

    initcreateGroupInfo(){
        if(!Client.getStore("createGroupInfo")) {
          let data = { // 群组信息
            faceUrl: '', // 群组头像
            groupName: '', // 群组名称
            groupMembers: [], // 邀请加群的好友列表
            // groupId: (new Date()).getTime(), // 群组ID
            groupType: 'Public', // 群组类型
            groupInfo: '', // 群组简介
            ApplyJoinOption: "", // 加群方式
          }
          Client.setStore("createGroupInfo", data);
        }
        // this.groupData.groupId = Client.getStore("createGroupInfo").groupId;
        this.groupData.groupId = (new Date()).getTime()/100;
        this.groupData.faceUrl = Client.getStore("createGroupInfo").faceUrl;
        this.groupData.groupName = Client.getStore("createGroupInfo").groupName;
        this.groupData.groupMembers = Client.getStore("createGroupInfo").groupMembers;
        this.groupData.groupType = Client.getStore("createGroupInfo").groupType;
        this.groupData.groupInfo = Client.getStore("createGroupInfo").groupInfo;
      },

    // 创建群组
    createGroup() {
              let member_list = [];
							for (let i = 0; i < this.groupData.groupMembers.length; i++) {
									if (this.groupData.groupMembers[i] && this.groupData.groupMembers.length > 0) {
                      member_list.push(this.groupData.groupMembers[i].friendId);
									}
							} 
							let faceurl = this.groupData.faceUrl;
							let cg_id = this.groupData.groupId;
							// if (cg_id && !/^[A-Za-z0-9_]+$/gi.test(cg_id)) {
              //     Toast({
              //       message: '群组ID只能是数字、字母或下划线',
              //       position: 'bottom',
              //       duration: 3000
              //     });
							// 		return
              // }
              if (this.groupData.faceUrl == '') {
                  Toast('请上传群组头像');
									return;
							}
							if (this.groupData.groupName.length == 0) {
                  Toast('请输入群组名称');
									return;
              }
              if(this.groupData.groupId == '') {
                  Toast('网络错误，无法生成群组ID');
									return;
              }
							if (webim.Tool.trimStr(this.groupData.groupName).length == 0) {
                  Toast('您输入的群组名称全是空格,请重新输入');
									return;
							}
							if (webim.Tool.getStrBytes(this.groupData.groupName) > 30) {
                  Toast('您输入的群组名称超出限制(最长10个汉字)');
									return;
							}
							if (webim.Tool.getStrBytes(this.groupData.groupInfo) > 120) {
                  Toast('您输入的群组简介超出限制(最长40个汉字)');
									return;
							}
							let options = {
									'GroupId': cg_id,
									'Owner_Account': this.loginInfo.identifier,
									'Type': this.groupData.groupType, 
									'Name': this.groupData.groupName,
									'Introduction': this.groupData.groupInfo,
									'MemberList': member_list
							};
							if (faceurl) {
									options.FaceUrl = faceurl;
							}
							if (options["Type"] != 'Private') { //非私有群才支持ApplyJoinOption属性
									options.ApplyJoinOption = this.groupData.applyJoinType;
              } 
              console.log(options)
							webim.createGroup(
									options,
									(resp) => {
                      Client.removeStore("createGroupInfo");
                      MessageBox('提示', '创建群成功');
                      this.$router.push({path: '/AddressList?type=1'});
									},
									(err) => {
                    console.log(err);
                      console.log(options);
                      Client.errInfo();
                      // alert(err.ErrorInfo);
									}
							);
    },
    toTrim(str) {
      str = " sdfsd"
      return str.replace(/(^\s+)|(\s+$)/g, "");
    },
    changeStorage(storeName, field, changeData, save) {
      // 修改存储对象的数据
      //     storeName 存储的对象名
      //     field 需要修改的字段名称
      //     changeData 修改后的字段数据
      //     save 保存在某个对象上
       let createData = Client.getStore(storeName);
        if(!createData) return;
        createData[field] = changeData;
        Client.setStore(storeName, createData);
        if(save) {
          save = Client.getStore(storeName);
        }
    },
    

    // 设置群组公开类型
    selectedPublic() {
      this.groupData.groupType = 'Public';
      this.changeStorage('createGroupInfo', 'groupType', 'Public', null);

    },
    // 设置群组私有类型
    selectedPrivate() {
      this.groupData.groupType = 'Private';
      this.changeStorage('createGroupInfo', 'groupType', 'Private', null);
    },
    // 设置群组聊天室类型
    selectedChatRoom() {
      this.groupData.groupType = 'ChatRoom';
      this.changeStorage('createGroupInfo', 'groupType', 'ChatRoom', null);
    },
    freeaccess() {
      this.joinGroupType = "自由加入";
      this.groupData.applyJoinType = "FreeAccess";
    },
    needpermission() {
      this.joinGroupType = "需要验证";
      this.groupData.applyJoinType = "NeedPermission";
    },
    disableapply() {
      this.joinGroupType = "禁止加入";
      this.groupData.applyJoinType = "DisableApply";
    },

    //弹出设置群类型的层
    showgroupTypeWrap() {
      this.popup.groupTypeWrap = true;
    },
    //弹出设置群类型的层
    showchangeTypeWrap() {
      this.popup.changeTypeWrap = true;
    },

    renturnAddressList() {
      Client.removeStore("createGroupInfo");
      history.back();
    }
  },
  components: {
    'mtPopup': Popup
  }
  
}
</script>


<style scoped lang="less">
  #uploadForm {
    overflow: hidden;
    height: 0;
  }
  .friendItem {
    height: 0.6rem;
    display: flex;
    align-items: center;
    background-color: white;
    padding: 0 0.15rem;
    .circle {
      width: 0.2rem;
      height: 0.2rem;
      background-image: url('../../assets/img/icon_unsekected@3x.png');
      background-size: 100%;
      background-repeat: no-repeat;
      margin-right: 0.15rem;
    }
    .circleActive {
      background-image: url('../../assets/img/icon_designate01@3x.png')!important;
    }
    .defaultActive {
      background-image: url('../../assets/img/icon_selected01@3x.png')!important;
    }
    .friendImg {
      width: 0.4rem;
      height: 0.4rem;
      border-radius: 50%;
      margin-right: 0.06rem;
    }
    .friendName {
      width: 100%;
      height: 0.6rem;
      line-height: 0.6rem;
      position: relative;
      font-size: 0.16rem;
      .friendNameLine {
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 0;
        height: 1px;
        background-color: #E1E1E1;
      }
    }
  }
  .mint-toast {
    z-index: 2999!important;
    .mint-toast-text {
       color: white!important;
    }
  }
  .editNameWrapper {
      width: 100%;
      height: 100%;
      .editName{
        width: 100%;
        height: 100%;
        background: #F5F5F5;
        .setNameLine {
          height: 0.21rem;
        }
        .input {
          width: 100%;
          height: 0.5rem;
          text-indent: 0.15rem;
          background-color: white;
          color: #4A4A4A;
          font-size: 0.14rem;
          outline: none;
          font-weight: 400;
          border: none;
        }
      }
    }
</style>
<style lang="less" scoped>
  .mint-toast {
    z-index: 2999;
  }
  .wrapper {
    .header {
      width: 3.75rem;
      height: 0.5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      font-size: 0.16rem;
      border-bottom: 1px solid #f4f4f4;
      background-color: white!important;
      .return {
        color: #4A4A4A;
        width: 0.32rem;
        height: 0.16rem;
        font-size: 0.16rem;
        position: absolute;
        left: 0.15rem;
        top: 0.25rem;
        margin-top: -0.08rem;
      }
      .send {
        color: #4A4A4A;
        font-size: 0.16rem;
        position: absolute;
        right: 0.15rem;
      }
    }
    .groupItem {
      height: 0.8rem;
      padding: 0.15rem;
      display: flex;
      background-color: white;
      position: relative;
      justify-content: space-between;
      box-sizing: border-box;
      .Set {
          display: flex;
          align-items: center;
          font-size: 0.12rem;
          img {
            width: 0.15rem;
            height: 0.15rem;
            margin: 0;
          }
      }
      .icon {
        width: 0.15rem;
        height: 0.15rem;
        position: absolute;
        right: 0.15rem;
        top: 50%;
        margin-top: -0.07rem;
      }
      img {
        width: 0.5rem;
        height: 0.5rem;
        border-radius: 50%;
        margin: 0 0.1rem 0 0;
      }
    }
    .myCard {
      height: 0.5rem;
      background-color: white;
      padding: 0 0.15rem;
      .myCardTitle {
        height: 0.5rem;
        line-height: 0.5rem;
        display: flex;
        justify-content: space-between;
        font-size: 0.14rem;
        color: #4a4a4a;
        .Set {
          display: flex;
          align-items: center;
          img {
            width: 0.15rem;
          }
        }
      }
      .lineWrapper {
        height: 1px;
        .line {
          width: 3.45rem;
          height: 1px;
          background-color: #E5E5E5;
        }
      }
    }
    .divisionLine {
      height: 0.1rem;
      background-color: #F4F4F4;
    }
    .selectedFriendsTitle {
        height: 0.27rem;
        line-height: 0.27rem;
        background-color: #F4F4F4;
        padding: 0 0.15rem;
        color:#818181;
        font-size: 0.12rem;
    }
    .selectedFriends {
      height: 0.7rem;
      display: flex;
      justify-content: space-between;
      padding: 0 0.15rem;
      background-color: white;
      align-items: center;
      .friendList{
        display: flex;
        align-items: center;
        .icon {
          width: 0.20rem;
          height: 0.20rem;
          margin-right: 0.1rem;
        }
        .faceItem {
          img {
            width: 0.5rem;
            height: 0.5rem;
            float: left;
            border-radius: 50%;
            margin-right: 0.1rem;
          }
        }
      }
      .Set {
          display: flex;
          align-items: center;
          font-size: 0.12rem;
          img {
            width: 0.15rem;
            height: 0.15rem;
            margin: 0;
          }
      }
    }
    .groupInfo {
      height: 0.7rem;
      background-color: white;
      padding: 0.14rem 0.15rem;
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      .Set {
          display: flex;
          align-items: center;
          font-size: 0.12rem;
          img {
            width: 0.15rem;
            height: 0.15rem;
            margin: 0;
          }
        }
      .groupName {
        color: #4F4F4F;
        font-size: 0.14rem;
      }
      .text {
        padding-top: 0.05rem;
        font-size: 0.12rem;
        color: #818181;
        width: 3rem;
        height: .12rem;
        line-height: .12rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
</style>


